from qiniu import Auth, put_file, put_data, etag, urlsafe_base64_encode
from qiniu import BucketManager

from application.config import appSettings


class ExtQiniu:
    """
        七牛云扩展
    """

    qiniu = Auth(appSettings.qiniu_access_key, appSettings.qiniu_secret_key)

    # 要上传的空间
    bucket = appSettings.qiniu_bucket
    # 拼接下载的域名
    domain = appSettings.qiniu_domain

    @staticmethod
    def get_token():
        """
            获取上传token
        """
        token = __class__.qiniu.upload_token(__class__.bucket)
        return token

    @staticmethod
    def get_url(key):
        """
            获取下载链接
        """
        url = __class__.domain + '/' + key
        return url

    @staticmethod
    def put_data(key, data):
        """
            上传二进制数据
        """
        token = __class__.get_token()
        res = put_data(token, key, data)
        if 'error' in res:
            return False, res.error
        else:
            return True, res[0]

    @staticmethod
    def put_file(key, file):
        """
            上传文件
        """
        token = __class__.get_token()
        res = put_file(token, key, file)
        if 'error' in res:
            return False, res.error
        else:
            return True, res

    @staticmethod
    def delete_file(key):
        """
            删除文件
        """
        # 初始化BucketManager
        bucket = BucketManager(__class__.qiniu)
        res = bucket.delete(__class__.bucket, key)
        if 'error' in res:
            return False
        else:
            return True

    @staticmethod
    def file_exists(key):
        """
            判断文件是否存在
        """
        # 初始化BucketManager
        bucket = BucketManager(__class__.qiniu)
        res = bucket.stat(__class__.bucket, key)
        if res.status_code == 200:
            return True
        else:
            return False


__all__ = [
    'ExtQiniu'
]
